from flask_restful import Resource, Api
from flask import Blueprint, request, session
from libs.response import generate_response
from model.models import User, UserCommodityCart, Commodity, db

cartapi_bp = Blueprint("cartapi", __name__)
api = Api(cartapi_bp)


class CartApi(Resource):
    def get(self):
        tmp = []
        account = session.get("account")
        user = User.query.filter(User.account == account).first()  # 根据session找到用户

        commodity = UserCommodityCart.query.filter(UserCommodityCart.user_id == user.id).all()  # 根据用户id找到对应的购物车

        for i in commodity:
            tmp.append(Commodity.query.filter(Commodity.id == i.commodity_id).first().to_json())  # 根据购物车中的商品id找到对应的商品

        return generate_response(data=tmp, message="get success", status_code=2000)

    def delete(self, id_=None):  # 传递过来的id_是str类型
        if id_ is None:
            return generate_response(message="参数不完整", status_code=4001)
        try:
            int(id_)
        except Exception:
            return generate_response(message="传递的参数不合法", status_code=4001)
        account = session.get("account")
        user = User.query.filter(User.account == account).first()  # 根据session找到用户
        commodity = UserCommodityCart.query.filter(UserCommodityCart.user_id == user.id).all()  # 根据用户id找到对应的购物车
        for i in commodity:

            if id_ == str(i.commodity_id):
                # 满足多个条件的查询用逗号隔开
                cart = UserCommodityCart.query.filter(UserCommodityCart.user_id == user.id, UserCommodityCart.commodity_id == int(id_)).first()
                db.session.delete(cart)
                db.session.commit()
                return generate_response(message="delete success")
        else:
            return generate_response(message="not fount commodity", status_code=4000)


api.add_resource(CartApi, "/cartapi", "/cartapi/")
api.add_resource(CartApi, "/cartapi/<id_>", endpoint='cartapiid')
